import React, { useCallback } from 'react';
import { LogoutOutlined } from '@ant-design/icons';
import { Avatar, Menu, message, Spin } from 'antd';
import { history, useModel } from 'umi';
import { stringify } from 'querystring';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import type { MenuInfo } from 'rc-menu/lib/interface';

export type GlobalHeaderRightProps = {
  menu?: boolean;
};

// /**
//  * 退出登录，并且将当前的 url 保存
//  */
// const loginOut = async () => {
//   // await outLogin();
//   message.success("登出成功");
//   window.onbeforeunload = function () {
//     localStorage.removeItem("token");
// };
//   const {query = {}, pathname} = history.location;
//   const {redirect} = query;
//   // Note: There may be security issues, please note
//   if (window.location.pathname !== '/user/login' && !redirect) {
//     history.replace({
//       pathname: '/user/login',
//       search: stringify({
//         redirect: pathname,
//       }),
//     });
//   }
// };

/**
 * 退出登录，并且将当前的 url 不保存
 */
// const loginOut = async () => {
//   // await outLogin();
//   message.success("登出成功");
//   const {query = {}, pathname} = history.location;
//   const {redirect} = query;
//   // Note: There may be security issues, please note
//   if (window.location.pathname !== '/user/login' && !redirect) {
//     history.replace({
//       pathname: '/user/login',
//       search: stringify({
//         redirect: pathname,
//       }),
//     });
//   }
// };

const loginOut = async () => {
  // await outLogin();
  message.success('登出成功');

  window.onbeforeunload = function () {
    localStorage.removeItem('token');
  };

  // const {query = {}, pathname} = history.location;
  // const {redirect} = query;
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/user/login') {
    history.replace({
      pathname: '/user/login',
      search: stringify({}),
    });
  }
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({}) => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout' && initialState) {
        setInitialState({ ...initialState, currentUser: undefined });
        loginOut();
        return;
      }
      history.push(`/account/${key}`);
    },
    [initialState, setInitialState],
  );

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.name) {
    return loading;
  }

  const menuHeaderDropdown = (
    <Menu
      className={styles.menu}
      selectedKeys={[]}
      onClick={() => {
        return onMenuClick;
      }}
      items={[
        {
          key: 'logout',
          icon: <LogoutOutlined />,
          label: '退出登录',
          danger: false,
          onClick: (info: MenuInfo) => {
            if (info.key === 'logout') {
              setInitialState({ ...initialState, currentUser: undefined });
              loginOut();
            }
          },
        },
      ]}
    />
  );
  return (
    <HeaderDropdown overlay={menuHeaderDropdown}>
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar size="small" className={styles.avatar} src={currentUser.avatar} alt="avatar" />
        <span className={`${styles.name} anticon`}>{currentUser.name}</span>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
